<template>
  <div class='app-container'>
    <div class="app-box">
      <div class="day-top clearfix">
        <div class="top"  style="width:300px;">
          <span>出单时间：</span>
           <el-date-picker
            class='wd230'
            size="mini"
            value-format='yyyy-MM-dd'
            @change='getTime1'
            v-model="time1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <div class="top1" style="width:190px;">
          <span>下级机构：</span>
          <!-- <ztree-select class='wd210' v-model="organizationUnitId" :treedata="treeData" :childprops="childprops" @change='setSelectedId'></ztree-select> -->
          <el-select v-model="organizationUnitId" placeholder="请选择" size="mini" class="wd210"  style="width:120px;">
            <el-option
              v-for="item in treeData"
              :key="item.organizationId"
              :label="item.organizationName"
              :value="item.organizationId">
            </el-option>
          </el-select>
        </div>
        <div class="top1" style="    width: 170px;">
          <span>保险公司：</span>
          <el-select  style="    width: 100px;" size="mini" v-model="insuranceId" placeholder="请选择保险公司" >
							<el-option-group v-for="group in companies" :key="group.letter" :label="group.letter">
								<el-option v-for="item in group.insurances" :key="item.id" :label="item.insuranceName" :value="item.id">
								</el-option>
							</el-option-group>
						</el-select>
        </div>
        <div class="top1" style="    width: 165px;">
          <span>保险类型：</span>
          <el-select v-model="type1" placeholder="请选择" size="mini" style="width:90px;">
            <el-option
              v-for="item in types"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <el-dropdown split-button type="primary" @click="toSearch" size="mini" placement='bottom-end' class="day-dropdown" @command='toexport'>
          查询
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item style="width:87px; text-align:center;">导出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- <div class="unitbox"><span>(单位：万元)</span></div> -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="保单量" name="first"></el-tab-pane>
        <el-tab-pane label="总保费" name="second"></el-tab-pane>
        <el-tab-pane label="净保费" name="third"></el-tab-pane>
        <el-tab-pane label="总收入" name="fourth"></el-tab-pane>
        <el-tab-pane label="总支出" name="fifth"></el-tab-pane>
        <el-tab-pane label="利润" name="sixth"></el-tab-pane>
        <el-tab-pane label="利润率" name="seventh"></el-tab-pane>
      </el-tabs>
      <div id="moonChart" style="width:100%;height:350px;"></div>
      <div class="day-table">
         <el-table
          :data="tableData"
          stripe
          v-loading='tableloading'
          style="width: 100%">
          <el-table-column
            prop="signDate"
            label="日期"
            width="180">
          </el-table-column>
          <el-table-column
            label="保单量"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.policyAmount'>{{scope.row.policyAmount}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            label="总保费(万元)"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.totalPremium'>{{scope.row.totalPremium | numFilter}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
           <el-table-column
            label="净保费(万元)"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.totalNetPremium'>{{scope.row.totalNetPremium | numFilter}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
           <el-table-column
            label="总收入(万元)"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.income'>{{scope.row.income | numFilter}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
           <el-table-column
            label="总支出(万元)"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.expends'>{{scope.row.expends | numFilter}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
           <el-table-column
            label="利润(万元)"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.profit'>{{scope.row.profit | numFilter}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
           <el-table-column
            label="利润率"
            align="right">
            <template slot-scope="scope">
              <span v-if='scope.row.profitRate'>{{((scope.row.profitRate)*100).toFixed(2)}}%</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import ztreeSelect from "@/components/z-select/index.vue";
import echarts from "echarts";
export default {
  data() {
    return {
      time1: "",
      insuranceId: "",
      companies: [],
      treeData: [],
      //数组子级相关参数
      childprops: {
        name: "displayName", //显示名字
        children: "organizationUnits", //子级字段名
        lv: "level" //当前层级
      },
      organizationUnitId: "",
      type1: "",
      types: [
        {
          id: "",
          label: "不限"
        },
        {
          id: "2",
          label: "交强险"
        },
        {
          id: "1",
          label: "商业险"
        }
      ],
      tableloading: false,
      tableData: [],
      activeName:'second',
      a:'总保费',
      b:'agre',
      chart: null,
      activeName:'second',
      intervalnum:0,
      lineData:[],
      expectedData:[]
    };
  },
  components: {
    ztreeSelect
  },
  filters: {
    numFilter(val) {
      // 截取当前数据到小数点后两位
      // let realVal = Number(val).toFixed(2)
      // num.toFixed(2)获取的是字符串
      // return Number(realVal)
      if (val || val == 0) {
        val = val.toString().replace(/\$|\,/g, "");
        if (isNaN(val)) {
          val = "0";
        }
        let sign = val == (val = Math.abs(val));
        val = Math.floor(val * 100 + 0.50000000001);
        let cents = val % 100;
        val = Math.floor(val / 100).toString();
        if (cents < 10) {
          cents = "0" + cents;
        }
        for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
          val =
            val.substring(0, val.length - (4 * i + 3)) +
            "," +
            val.substring(val.length - (4 * i + 3));
        }

        return (sign ? "" : "-") + val + "." + cents;
      }
    }
  },
  mounted() {
    this.getCompanies();
    this.getUnits();
    if (this.$route.query.month) {
      let val = this.$route.query.month;
      let year = val.split("-")[0];
      let month = val.split("-")[1];
      var day = new Date(year, month, 0);
      var lastdate = year + "-" + month + "-" + day.getDate(); //获取月份的最后一天
      let a = val + "-01";
      let arr = [];
      arr.push(a);
      arr.push(lastdate);
      this.time1 = arr;
    }else if (this.$route.query.startDay) {
      this.time1 = [this.$route.query.startDay, this.$route.query.endDay];
    } else {
      this.getTimeNow();
    }
    if (this.$route.query.ins) {
      this.insuranceId = this.$route.query.ins;
    }
    if (this.$route.query.org) {
      this.organizationUnitId = Number(this.$route.query.org);
    }
    if (this.$route.query.type) {
      this.type1 = this.$route.query.type;
    }
    if(this.$route.query.active){
      this.activeName = this.$route.query.active;
    }
    this.getDay();
  },
  watch:{
    $route(to, from) {
      if (this.$route.query.month) {
        let val = this.$route.query.month;
        let year = val.split("-")[0];
        let month = val.split("-")[1];
        var day = new Date(year, month, 0);
        var lastdate = year + "-" + month + "-" + day.getDate(); //获取月份的最后一天
        let a = val + "-01";
        let arr = [];
        arr.push(a);
        arr.push(lastdate);
        this.time1 = arr;
      }else if (this.$route.query.startDay) {
        this.time1 = [this.$route.query.startDay, this.$route.query.endDay];
      } else {
        this.getTimeNow();
      }
      if (this.$route.query.ins) {
        this.insuranceId = this.$route.query.ins;
      }
      if (this.$route.query.org) {
        this.organizationUnitId = Number(this.$route.query.org);
      }
      if (this.$route.query.type) {
        this.type1 = this.$route.query.type;
      }
      if(this.$route.query.active){
        this.activeName = this.$route.query.active;
      }
      this.getDay();
    }
  },
  computed: {},
  created() {},
  methods: {
    // 公司
    getCompanies() {
      let that = this;
      let all = {
        letter: "",
        insurances: [{ insuranceName: "全部", id: "" }]
      };
      let params = {};
      this.post(params, "services/app/common/GetGroupInsurances").then(rs => {
        console.log(rs);
        if (rs.success) {
          let result = rs.result.items;
          result.unshift(all);
          that.companies = result;
        }
      });
    },
    // 机构
    getUnits() {
      let params = {};
      let all = {
        organizationId:'',
        organizationName:'全部机构'
      };
      this.post(params, "services/app/common/ChildOrganizations").then(rs => {
        console.log(rs);
        if (rs.success) {
          let result = rs.result;
          result.unshift(all);
          this.treeData = result;
        }
      });
    },
    //获取时间
    getTimeNow() {
      var arr = [];
      var endDay = this.getNowFormatDate(0).substring(8, 10);
      let yesDay = Number(endDay)-1;
      if(yesDay<10){
        yesDay = '0'+yesDay;
      }
      if (endDay != '01') {
        arr[0] = this.getNowFormatDate(0).substring(0, 8) + "01";
        arr[1] = this.getNowFormatDate(0).substring(0, 8) + yesDay; //ok
      } else {
        arr[0] = this.getNowFormatDate(1).substring(0, 8) + "01";
        arr[1] = this.getNowFormatDate(1).substring(0, 8) + this.mGetDate(1); //ok
      }
      this.time1 = arr;
    },
    //获取当前时间，格式YYYY-MM-DD
    getNowFormatDate(mon) {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1 - mon;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    //获取当前月份天数
    mGetDate(mon) {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1 - mon;
      var d = new Date(year, month, 0);
      return d.getDate();
    },
    // 表格
    getDay() {
      let params = {
        beginDate: this.time1[0],
        endDate: this.time1[1],
        organizationId: this.organizationUnitId,
        insuranceId: this.insuranceId,
        guaranteeSlipType: this.type1
      };
      this.tableloading = true;
      this.post(params, "services/app/report/Target_Days").then(rs => {
        this.tableloading = false;
        if (rs.success) {
          if (rs.result) {
            this.tableData = rs.result.items;
            if(this.tableData.length >= 24){
              this.intervalnum = Math.floor(this.tableData.length/12);
            }
            this.getLineData(this.activeName);
          }
        }else{
            this.$notify.error({
              title: "错误",
              message: rs.error.message
            });
        	}
      });
    },
    setSelectedId(val) {
      this.organizationUnitId = val;
    },
    // tabs
    handleClick(tab){
      this.getLineData(tab.name);
    },
    getLineData(name){
      console.log(name);
      if(name == 'first'){
        this.lineData = this.mapArr(this.tableData,'policyAmount');
        this.a = '保单量';
      }else if(name == 'second'){
        this.lineData = this.mapArr(this.tableData,'totalPremium');
        this.a = '总保费';
      }else if(name == 'third'){
        this.lineData = this.mapArr(this.tableData,'totalNetPremium');
        this.a = '净保费';
      }else if(name == 'fourth'){
        this.lineData = this.mapArr(this.tableData,'income');
        this.a = '总收入';
      }else if(name == 'fifth'){
        this.lineData = this.mapArr(this.tableData,'expends');
        this.a = '总支出';
      }else if(name == 'sixth'){
        this.lineData = this.mapArr(this.tableData,'profit');
        this.a = '利润';
      }else if(name == 'seventh'){
        this.lineData = this.mapArr(this.tableData,'profitRate');
        this.a = '利润率';
      }
      this.loadEchart();
    },
    // 遍历列
    mapArr(data,name){
      let arr = [];
      if(name == 'signDate'){
        data.map(function(item){
          if(item[name]!== null){
            arr.push(item[name].substring(0,10))
          }else{
            arr.push(0)
          }
        })
      }else{
        data.map(function(item){
          if(item[name]!== null){
            arr.push(item[name])
          }else{
            arr.push(0)
          }
        })
      }
      return arr
    },
    getTime1(val) {
      console.log(val);
    },
    // 搜索
    toSearch() {
      // console.log(this.time1)
      // return
      if(this.time1 != null){
         this.$router.push({
          name:'dayform',
          query:{
            startDay:this.time1[0],
            endDay :this.time1[1],
            org :this.organizationUnitId,
            ins :this.insuranceId,
            type : this.type1,
            active:this.activeName,
            time:new Date().getTime()
          }
        })
      }else{
         this.$message.error('请输入出单时间');
      }
     
    },
    // 导出
    toexport() {
      let params = {
        beginDate: this.time1[0],
        endDate: this.time1[1],
        organizationId: this.organizationUnitId,
        insuranceId: this.insuranceId,
        guaranteeSlipType: this.type1
      };
      this.post(params, "services/app/report/Target_Days_Export").then(rs => {
        if (rs.success) {
          if (rs.result) {
             let filePath=rs.result.filePath
             console.log(filePath)
             window.location.href=filePath
          }
        }else{
            this.$notify.error({
              title: "错误",
              message: rs.error.message
            });
        	}
      });
    },
    // 图
    loadEchart() {
      const data = this.tableData;
      this.chart = echarts.init(document.getElementById("moonChart"));
      if(this.activeName == 'first'){
        this.setOptions(this.mapArr(data,'signDate'),this.a,this.intervalnum,this.mapArr(data,'policyAmount'),'万元');
      }else  if(this.activeName == 'seventh'){
        this.setOptions(this.mapArr(data,'signDate'),this.a,this.intervalnum,this.mapArr(data,'profitRate'),'百分比');
      }else{
        this.setOptions(this.mapArr(data,'signDate'),this.a,this.intervalnum,this.lineData,'万元');
      }
    },
    setOptions(columns,a,num,expectedData,unitname) {
      console.log("dsadasdsad-----");
      this.chart.setOption({
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: columns,
          // boundaryGap: ['20%', '20%'],
          // boundaryGap: true,
          axisTick: {
            show: false
          },
          axisLabel:{
            fontSize:11,
            interval:num,
            rotate:60
            // formatter:function(value)
            //   {
            //       return value.split("").join("\n");
            //   }

          },
          splitLine:{
            show:true
          },
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        toolbox: {
            show: true,
            right:20,
            feature: {
                // dataZoom: {
                //     yAxisIndex: 'none'
                // },
                // dataView: {readOnly: false},
                magicType: {type: ['line', 'bar']},
                // restore: {},
                saveAsImage: {}
            }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross"
          },
          padding: [5, 10]
        },
        yAxis: {
          name:unitname,
          type: 'value',
          axisTick: {
            show: false
          },
          splitLine:{
            show:false
          },
        },
        legend: {
          data: [a]
        },
        series: [
          {
            name: a,
            itemStyle: {
              normal: {
                color: "#409EFF",
                lineStyle: {
                  color: "#409EFF",
                  width: 2
                },
              }
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(64,158,255,0.5)'
                    }, {
                        offset: 0.3,
                        color: 'rgba(64,158,255,0.1)'
                    },{
                        offset: 1,
                        color: 'rgba(64,158,255,0)'
                    }])
                }
            },
            // smooth: true,
            type: 'line',
            symbolSize:6,
            data: expectedData,
            animationDuration: 2800,
            animationEasing: "cubicInOut"
          },
        ]
      });
    },
  }
};
</script>
<style lang="scss" scoped>
.wd210 {
  width: 160px;
}
.wd230 {
  width: 230px;
}
.app-box {
  color: #333;
  .day-top {
    margin-bottom: 15px;
    color: #666;
    .top {
      display: inline-block;
      width: 315px;
      margin-bottom: 15px;
    }
    .top1 {
      display: inline-block;
      width: 240px;
      margin-left: 10px
    }
  }
  .unitbox {
    height: 40px;
    line-height: 40px;
    span {
      font-weight: 600;
    }
  }
  .day-table {
    margin-top: 30px;
  }
}
 @media screen and (min-width: 1380px)  {
   .top1 {
     margin-left: 30px;
   }
   .day-dropdown{
     margin-left: 100px;
   }
 }
// @media screen and (min-width: 1280px) and (max-width: 1380px) {
//   .wd210 {
//     width: 130px;
//   }
//   .wd230 {
//     width: 220px;
//   }
//   .app-box {
//     .day-top {
//       .top {
//         float: left;
//         width: 30%;
//       }
//       .top1 {
//         float: left;
//         width: 20%;
//       }
//     }
//   }
// }
</style>